#!/usr/bin/env Rscript

## ####################
## Package Dependencies
## ####################

suppressMessages({
    library("pscl")
    library("foreach")
    library("doRNG")
    library("emIRT")
    library("plyr")
}
                 )

## ##############
## Define Handoff
## ##############

BATON <- new.env()

## ################
## Env Dependencies
## ################

isDistMem <- as.integer(Sys.getenv("DISTMEM"))
cCHAM <- Sys.getenv("CHAM")

## ############################
## Shared or Distributed Memory
## ############################

if (isDistMem == 1) {
    suppressMessages({
        library("doMPI")
    }
                     )
    cl <- startMPIcluster()
    registerDoMPI(cl)
} else {
    suppressMessages({
        library("doMC")
    }
                     )
    registerDoMC(4)
}
registerDoRNG()

## ############
## Set Up Paths
## ############

p2root <- "../../../"
p2common <- file.path(p2root, "../common/")
p2funcs <- paste(p2root, "src/R/functions/", sep = "")
p2rc <- paste(p2common, "data/RDA/rollcalls/", sep = "")
p2output <- paste(p2root, "data/RDATA/bootstrap/", cCHAM, ".Rdata", sep = "")
p2est <- paste(p2root, "data/RDATA/estimates/fastest/", cCHAM, ".Rdata", sep = "")

BATON <- new.env()
BATON$p2rc <- p2rc

## ####
## Data
## ####

load(p2est)

dfMeta <- adply(1:length(lOut),
                1,
                .fun = function(X) return(
                    data.frame(idx = X,
                               mc = lOut[[X]]$mc,
                               cham = lOut[[X]]$cham,
                               sess = lOut[[X]]$sess
                               )
                    )
                )

dfMeta1 <- subset(dfMeta, mc == 1)

length(lOut)
lOut <- lOut[dfMeta1$idx]
length(lOut)


BATON$lOut <- lOut

## #####################
## Estimate Ideal Points
## #####################

set.seed(1)

g <- 1

G <- length(lOut)

lOut <- foreach(g = 1:G,
                .export = "BATON"
                ) %dopar% {
                    ## #########################
                    ## Attach Handed Off Objects
                    ## #########################

                    attach(BATON)
                    source(file.path(p2funcs, "runPBS.r"))

                    ## ##################
                    ## Get Current Params
                    ## ##################

                    thisout <- lOut[[g]]

                    cham <- thisout$cham
                    sess <- thisout$sess

                    load(paste(p2rc, "/", cham, sess, ".rda", sep = ""))
                    rc <- rcs$all

                    priors <- makePriors(thisout$output$output$n,
                                         thisout$output$output$j,
                                         thisout$output$output$d
                                         )

                    lOutBS <- runPBS(.output = thisout$output$output,
                                     .priors = priors,
                                     .bsiter = 1000,
                                     .rc = rc,
                                     .asEM = TRUE,
                                     .thresh = 1e-6
                                     )

                    thisout$output$output$varsBS <- lOutBS
                    return(thisout)
                }

## ###########
## Save Output
## ###########

length(lOut)

save(lOut,
     file = p2output
     )

## #####################
## Shut Down Dist Memory
## #####################
if (isDistMem == 1) {
    closeCluster(cl)
    mpi.quit()
}

################################################################################
